package l1j.server.server.datatables.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.datatables.storage.HellTimeStorage;
import l1j.server.server.templates.L1HellTime;
import l1j.server.server.utils.PerformanceTimer;
import l1j.server.server.utils.SQLUtil;

public class HellTimeTable implements HellTimeStorage{
	private static Logger _log = Logger.getLogger(HellTimeTable.class.getName());
	
	private static HellTimeTable _instance;

	public static HellTimeTable getInstance() {
		if (_instance == null) {
			_instance = new HellTimeTable();
		}
		return _instance;
	}
	
	private final HashMap<Integer , L1HellTime> _objidmap =new HashMap<Integer , L1HellTime>();

	/**
	 * 預先加載地獄時間資料
	 */
	@Override
	public void load() {
		{
			final PerformanceTimer timer = new PerformanceTimer();
			Connection cn = null;
			PreparedStatement ps = null;
			ResultSet rs = null;
			try {
				cn = DatabaseFactory.get().getConnection();
				ps = cn.prepareStatement("SELECT * FROM characters where HellTime !=0");
				rs = ps.executeQuery();
				while (rs.next()) {
					final int objid = rs.getInt("objid");
					final int helltime = rs.getInt("HellTime");
					final L1HellTime temp = new L1HellTime(objid, helltime);
					_objidmap.put(objid, temp);
				}
			} catch (final SQLException e) {
				_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
			} finally {
				SQLUtil.close(rs);
				SQLUtil.close(ps);
				SQLUtil.close(cn);
			}
			_log.info("載入坐牢清單紀錄數量: " + this._objidmap.size() + "(" + timer.get() + "ms)");
		}
	}

	@Override
	public HashMap<Integer, L1HellTime> getObjidList() {
		return _objidmap;
	}
	
	@Override
	public L1HellTime getTempByObjid(final int objid) {
			return _objidmap.get(objid);
	}


	@Override
	public void BeginHell(final int objid , final int helltime) {
		L1HellTime temp = _objidmap.get(objid);
		if(temp == null){
			temp = new L1HellTime(objid , helltime);
			_objidmap.put(objid, temp);
		}else {
			if(temp.getHelltime() !=helltime){
			temp.setHellTime(helltime);
			}
			if(!_objidmap.containsKey(objid)){
				_objidmap.put(objid, temp);
			}
		}
	}

	@Override
	public void EndHell(final int objid) {
		final L1HellTime temp = _objidmap.get(objid);
		if(temp == null){
			return;
		}
		_objidmap.remove(objid);
	}

	@Override
	public Set<Integer> getOrderSet() {
		return _objidmap.keySet();
	}

	
}
